package com.maodou.core.ui.components.textfield

import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.*
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.maodou.core.ui.components.textfield.AppTextField
import com.maodou.core.ui.components.textfield.BorderlessTextField
import com.maodou.core.ui.components.textfield.FormField
import com.maodou.core.ui.components.textfield.InputValidator
import com.maodou.core.ui.components.textfield.MultilineTextField
import com.maodou.core.ui.components.textfield.PasswordField
import com.maodou.core.ui.components.textfield.SearchField
import com.maodou.core.ui.components.textfield.TextFieldType
import com.maodou.core.ui.components.textfield.TypedBorderlessTextField
import com.maodou.core.ui.components.textfield.TypedTextField
import com.maodou.core.ui.components.textfield.ValidationResult
import com.maodou.core.ui.components.textfield.Validators

/**
 * 输入框组件使用示例
 * 展示各种类型的输入框及其使用场景
 */
@Composable
fun TextFieldExamples() {
    // 状态管理
    var basicText by remember { mutableStateOf("") }
    var emailText by remember { mutableStateOf("") }
    var phoneText by remember { mutableStateOf("") }
    var passwordText by remember { mutableStateOf("") }
    var confirmPasswordText by remember { mutableStateOf("") }
    var searchText by remember { mutableStateOf("") }
    var multilineText by remember { mutableStateOf("") }
    var numberText by remember { mutableStateOf("") }
    var decimalText by remember { mutableStateOf("") }
    var urlText by remember { mutableStateOf("") }
    var idCardText by remember { mutableStateOf("") }
    var bankCardText by remember { mutableStateOf("") }
    var requiredText by remember { mutableStateOf("") }
    var customValidationText by remember { mutableStateOf("") }
    
    // 无边框输入框状态
    var borderlessText by remember { mutableStateOf("") }
    var borderlessEmailText by remember { mutableStateOf("") }
    var borderlessSearchText by remember { mutableStateOf("") }
    var borderlessNumberText by remember { mutableStateOf("") }
    
    // 焦点管理
    val focusRequesters = remember { List(15) { FocusRequester() } }
    
    LazyColumn(
        modifier = Modifier
            .fillMaxSize()
            .padding(16.dp),
        verticalArrangement = Arrangement.spacedBy(16.dp)
    ) {
        item {
            Text(
                text = "输入框组件示例",
                style = MaterialTheme.typography.headlineMedium,
                fontWeight = FontWeight.Bold
            )
        }
        
        // 基础输入框
        item {
            ExampleSection("基础输入框") {
                Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
                    AppTextField(
                        value = basicText,
                        onValueChange = { basicText = it },
                        label = "基础文本输入",
                        placeholder = "请输入文本",
                        supportingText = "这是一个基础的文本输入框",
                        maxLength = 50,
                        focusRequester = focusRequesters[0]
                    )
                    
                    AppTextField(
                        value = basicText,
                        onValueChange = { basicText = it },
                        label = "带图标的输入框",
                        placeholder = "请输入内容",
                        leadingIcon = Icons.Default.Person,
                        trailingIcon = Icons.Default.Clear,
                        onTrailingIconClick = { basicText = "" }
                    )
                }
            }
        }
        
        // 类型化输入框
        item {
            ExampleSection("类型化输入框") {
                Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
                    TypedTextField(
                        value = emailText,
                        onValueChange = { emailText = it },
                        type = TextFieldType.Email,
                        label = "邮箱地址",
                        placeholder = "example@domain.com",
                        supportingText = "请输入有效的邮箱地址"
                    )
                    
                    TypedTextField(
                        value = phoneText,
                        onValueChange = { phoneText = it },
                        type = TextFieldType.Phone,
                        label = "手机号码",
                        placeholder = "请输入11位手机号",
                        supportingText = "仅支持中国大陆手机号"
                    )
                    
                    TypedTextField(
                        value = numberText,
                        onValueChange = { numberText = it },
                        type = TextFieldType.Number,
                        label = "数字输入",
                        placeholder = "请输入数字",
                        maxLength = 10
                    )
                    
                    TypedTextField(
                        value = decimalText,
                        onValueChange = { decimalText = it },
                        type = TextFieldType.Decimal,
                        label = "小数输入",
                        placeholder = "请输入小数",
                        supportingText = "支持小数点"
                    )
                }
            }
        }
        
        // 密码输入框
        item {
            ExampleSection("密码输入框") {
                Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
                    PasswordField(
                        value = passwordText,
                        onValueChange = { passwordText = it },
                        label = "密码",
                        placeholder = "请输入密码",
                        supportingText = "密码长度至少6位",
                        validator = Validators.minLength(6, "密码至少需要6个字符")
                    )
                    
                    PasswordField(
                        value = confirmPasswordText,
                        onValueChange = { confirmPasswordText = it },
                        label = "确认密码",
                        placeholder = "请再次输入密码",
                        validator = InputValidator { input ->
                            if (input != passwordText) {
                                ValidationResult(false, "两次输入的密码不一致")
                            } else {
                                ValidationResult(true)
                            }
                        }
                    )
                }
            }
        }
        
        // 搜索框
        item {
            ExampleSection("搜索框") {
                SearchField(
                    value = searchText,
                    onValueChange = { searchText = it },
                    placeholder = "搜索商品、品牌或关键词",
                    onSearch = { query ->
                        // 处理搜索逻辑
                        println("搜索: $query")
                    }
                )
            }
        }
        
        // 多行文本输入框
        item {
            ExampleSection("多行文本输入框") {
                MultilineTextField(
                    value = multilineText,
                    onValueChange = { multilineText = it },
                    label = "详细描述",
                    placeholder = "请输入详细描述信息...",
                    minLines = 3,
                    maxLines = 6,
                    maxLength = 500,
                    supportingText = "请详细描述您的需求或问题"
                )
            }
        }
        
        // 特殊格式输入框
        item {
            ExampleSection("特殊格式输入框") {
                Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
                    TypedTextField(
                        value = urlText,
                        onValueChange = { urlText = it },
                        type = TextFieldType.Url,
                        label = "网址",
                        placeholder = "https://example.com",
                        supportingText = "请输入完整的网址"
                    )
                    
                    TypedTextField(
                        value = idCardText,
                        onValueChange = { idCardText = it },
                        type = TextFieldType.IdCard,
                        label = "身份证号",
                        placeholder = "请输入18位身份证号",
                        supportingText = "请输入有效的身份证号码"
                    )
                    
                    TypedTextField(
                        value = bankCardText,
                        onValueChange = { bankCardText = it },
                        type = TextFieldType.BankCard,
                        label = "银行卡号",
                        placeholder = "请输入银行卡号",
                        supportingText = "卡号会自动格式化显示"
                    )
                }
            }
        }
        
        // 表单输入框
        item {
            ExampleSection("表单输入框") {
                Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
                    FormField(
                        value = requiredText,
                        onValueChange = { requiredText = it },
                        label = "姓名",
                        placeholder = "请输入您的姓名",
                        required = true,
                        maxLength = 20
                    )
                    
                    FormField(
                        value = customValidationText,
                        onValueChange = { customValidationText = it },
                        label = "用户名",
                        placeholder = "请输入用户名",
                        required = true,
                        supportingText = "用户名只能包含字母、数字和下划线",
                        validator = InputValidator { input ->
                            if (input.isEmpty()) {
                                ValidationResult(false, "用户名不能为空")
                            } else if (!input.matches(Regex("^[a-zA-Z0-9_]+$"))) {
                                ValidationResult(false, "用户名只能包含字母、数字和下划线")
                            } else if (input.length < 3) {
                                ValidationResult(false, "用户名至少需要3个字符")
                            } else {
                                ValidationResult(true)
                            }
                        }
                    )
                }
            }
        }
        
        // 状态示例
        item {
            ExampleSection("输入框状态") {
                Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
                    AppTextField(
                        value = "只读文本",
                        onValueChange = { },
                        label = "只读输入框",
                        readOnly = true,
                        supportingText = "此输入框为只读状态"
                    )
                    
                    AppTextField(
                        value = "禁用文本",
                        onValueChange = { },
                        label = "禁用输入框",
                        enabled = false,
                        supportingText = "此输入框已禁用"
                    )
                    
                    AppTextField(
                        value = "错误文本",
                        onValueChange = { },
                        label = "错误状态",
                        isError = true,
                        errorMessage = "输入内容有误",
                        supportingText = "这是错误状态的输入框"
                    )
                }
            }
        }
        
        // 无边框输入框示例
        item {
            ExampleSection("无边框输入框") {
                Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
                    Text(
                        text = "所有输入框组件都支持borderless参数，可以动态切换有边框和无边框样式",
                        style = MaterialTheme.typography.bodyMedium,
                        color = MaterialTheme.colorScheme.onSurfaceVariant
                    )
                    
                    // 基础无边框输入框
                    AppTextField(
                        value = borderlessText,
                        onValueChange = { borderlessText = it },
                        label = "基础无边框输入框",
                        placeholder = "请输入文本",
                        borderless = true,
                        modifier = Modifier.padding(8.dp)
                    )
                    
                    // 带图标的无边框输入框
                    AppTextField(
                        value = borderlessText,
                        onValueChange = { borderlessText = it },
                        label = "带图标的无边框输入框",
                        placeholder = "请输入内容",
                        leadingIcon = Icons.Default.Person,
                        trailingIcon = if (borderlessText.isNotEmpty()) Icons.Default.Clear else null,
                        onTrailingIconClick = if (borderlessText.isNotEmpty()) {{ borderlessText = "" }} else null,
                        borderless = true,
                        modifier = Modifier.padding(8.dp)
                    )
                    
                    // 类型化无边框输入框
                    TypedTextField(
                        value = borderlessEmailText,
                        onValueChange = { borderlessEmailText = it },
                        type = TextFieldType.Email,
                        label = "邮箱地址（无边框）",
                        placeholder = "请输入邮箱",
                        borderless = true,
                        modifier = Modifier.padding(8.dp)
                    )
                    
                    // 搜索框无边框
                    SearchField(
                        value = borderlessSearchText,
                        onValueChange = { borderlessSearchText = it },
                        placeholder = "搜索（无边框）",
                        borderless = true,
                        modifier = Modifier.padding(8.dp)
                    )
                    
                    // 密码框无边框
                    PasswordField(
                        value = passwordText,
                        onValueChange = { passwordText = it },
                        label = "密码（无边框）",
                        placeholder = "请输入密码",
                        borderless = true,
                        modifier = Modifier.padding(8.dp)
                    )
                    
                    // 多行文本无边框
                    MultilineTextField(
                        value = multilineText,
                        onValueChange = { multilineText = it },
                        label = "多行文本（无边框）",
                        placeholder = "请输入多行文本...",
                        minLines = 2,
                        maxLines = 4,
                        borderless = true,
                        modifier = Modifier.padding(8.dp)
                    )
                    
                    TypedTextField(
                        value = borderlessNumberText,
                        onValueChange = { borderlessNumberText = it },
                        type = TextFieldType.Number,
                        label = "数字输入（无边框）",
                        placeholder = "请输入数字",
                        borderless = true,
                        maxLength = 10,
                        modifier = Modifier.padding(8.dp)
                    )
                }
            }
        }
        
        // 操作按钮
        item {
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.spacedBy(12.dp)
            ) {
                Button(
                    onClick = {
                        // 清空所有输入
                        basicText = ""
                        emailText = ""
                        phoneText = ""
                        passwordText = ""
                        confirmPasswordText = ""
                        searchText = ""
                        multilineText = ""
                        numberText = ""
                        decimalText = ""
                        urlText = ""
                        idCardText = ""
                        bankCardText = ""
                        requiredText = ""
                        customValidationText = ""
                        borderlessText = ""
                        borderlessEmailText = ""
                        borderlessSearchText = ""
                        borderlessNumberText = ""
                    },
                    modifier = Modifier.weight(1f)
                ) {
                    Text("清空所有")
                }
                
                Button(
                    onClick = {
                        // 填充示例数据
                        basicText = "示例文本"
                        emailText = "user@example.com"
                        phoneText = "13800138000"
                        passwordText = "123456"
                        confirmPasswordText = "123456"
                        searchText = "搜索关键词"
                        multilineText = "这是一个多行文本示例\n可以输入多行内容\n支持换行显示"
                        numberText = "12345"
                        decimalText = "123.45"
                        urlText = "https://www.example.com"
                        idCardText = "110101199001011234"
                        bankCardText = "6222021234567890"
                        requiredText = "张三"
                        customValidationText = "user_123"
                        borderlessText = "无边框文本"
                        borderlessEmailText = "borderless@example.com"
                        borderlessSearchText = "无边框搜索"
                        borderlessNumberText = "54321"
                    },
                    modifier = Modifier.weight(1f)
                ) {
                    Text("填充示例")
                }
            }
        }
        
        // 使用说明
        item {
            Card(
                modifier = Modifier.fillMaxWidth(),
                colors = CardDefaults.cardColors(
                    containerColor = MaterialTheme.colorScheme.surfaceVariant
                )
            ) {
                Column(
                    modifier = Modifier.padding(16.dp),
                    verticalArrangement = Arrangement.spacedBy(8.dp)
                ) {
                    Text(
                        text = "使用说明",
                        style = MaterialTheme.typography.titleMedium,
                        fontWeight = FontWeight.Bold
                    )
                    
                    Text(
                        text = "• AppTextField: 基础通用输入框，支持各种自定义配置，包括borderless参数",
                        style = MaterialTheme.typography.bodyMedium
                    )
                    
                    Text(
                        text = "• TypedTextField: 类型化输入框，根据类型自动配置键盘和验证，支持borderless模式",
                        style = MaterialTheme.typography.bodyMedium
                    )
                    
                    Text(
                        text = "• FormField: 表单输入框，支持必填标记和自定义验证，支持borderless模式",
                        style = MaterialTheme.typography.bodyMedium
                    )
                    
                    Text(
                        text = "• SearchField: 搜索框，优化了搜索场景的交互，支持borderless模式",
                        style = MaterialTheme.typography.bodyMedium
                    )
                    
                    Text(
                        text = "• PasswordField: 密码输入框，支持密码可见性切换，支持borderless模式",
                        style = MaterialTheme.typography.bodyMedium
                    )
                    
                    Text(
                        text = "• MultilineTextField: 多行文本输入框，适用于长文本输入，支持borderless模式",
                        style = MaterialTheme.typography.bodyMedium
                    )
                    
                    Text(
                        text = "• borderless参数: 所有输入框组件都支持borderless=true来实现无边框样式",
                        style = MaterialTheme.typography.bodyMedium,
                        color = MaterialTheme.colorScheme.primary
                    )
                    
                    Text(
                        text = "• BorderlessTextField: 专门的无边框输入框，基于TextField实现（已弃用，建议使用borderless参数）",
                        style = MaterialTheme.typography.bodyMedium,
                        color = MaterialTheme.colorScheme.onSurfaceVariant
                    )
                }
            }
        }
    }
}

/**
 * 示例区域组件
 */
@Composable
fun ExampleSection(
    title: String,
    content: @Composable () -> Unit
) {
    Card(
        modifier = Modifier.fillMaxWidth(),
        elevation = CardDefaults.cardElevation(defaultElevation = 2.dp)
    ) {
        Column(
            modifier = Modifier.padding(16.dp),
            verticalArrangement = Arrangement.spacedBy(12.dp)
        ) {
            Text(
                text = title,
                style = MaterialTheme.typography.titleMedium,
                fontWeight = FontWeight.SemiBold,
                color = MaterialTheme.colorScheme.primary
            )
            
            content()
        }
    }
}

/**
 * 登录表单示例
 */
@Composable
fun LoginFormExample() {
    var username by remember { mutableStateOf("") }
    var password by remember { mutableStateOf("") }
    var rememberMe by remember { mutableStateOf(false) }
    
    Card(
        modifier = Modifier
            .fillMaxWidth()
            .padding(16.dp),
        elevation = CardDefaults.cardElevation(defaultElevation = 4.dp)
    ) {
        Column(
            modifier = Modifier.padding(24.dp),
            verticalArrangement = Arrangement.spacedBy(16.dp)
        ) {
            Text(
                text = "登录",
                style = MaterialTheme.typography.headlineSmall,
                fontWeight = FontWeight.Bold,
                modifier = Modifier.align(Alignment.CenterHorizontally)
            )
            
            FormField(
                value = username,
                onValueChange = { username = it },
                label = "用户名",
                placeholder = "请输入用户名或邮箱",
                required = true,
                type = TextFieldType.Text,
                validator = Validators.required("请输入用户名")
            )
            
            PasswordField(
                value = password,
                onValueChange = { password = it },
                label = "密码",
                placeholder = "请输入密码",
                validator = Validators.required("请输入密码")
            )
            
            Row(
                modifier = Modifier.fillMaxWidth(),
                verticalAlignment = Alignment.CenterVertically
            ) {
                Checkbox(
                    checked = rememberMe,
                    onCheckedChange = { rememberMe = it }
                )
                Text(
                    text = "记住我",
                    style = MaterialTheme.typography.bodyMedium,
                    modifier = Modifier.padding(start = 8.dp)
                )
            }
            
            Button(
                onClick = {
                    // 处理登录逻辑
                    println("登录: $username, $password, 记住我: $rememberMe")
                },
                modifier = Modifier.fillMaxWidth(),
                enabled = username.isNotBlank() && password.isNotBlank()
            ) {
                Text("登录")
            }
        }
    }
}

/**
 * 注册表单示例
 */
@Composable
fun RegisterFormExample() {
    var username by remember { mutableStateOf("") }
    var email by remember { mutableStateOf("") }
    var phone by remember { mutableStateOf("") }
    var password by remember { mutableStateOf("") }
    var confirmPassword by remember { mutableStateOf("") }
    var agreeTerms by remember { mutableStateOf(false) }
    
    Card(
        modifier = Modifier
            .fillMaxWidth()
            .padding(16.dp),
        elevation = CardDefaults.cardElevation(defaultElevation = 4.dp)
    ) {
        Column(
            modifier = Modifier
                .padding(24.dp)
                .verticalScroll(rememberScrollState()),
            verticalArrangement = Arrangement.spacedBy(16.dp)
        ) {
            Text(
                text = "注册账号",
                style = MaterialTheme.typography.headlineSmall,
                fontWeight = FontWeight.Bold,
                modifier = Modifier.align(Alignment.CenterHorizontally)
            )
            
            FormField(
                value = username,
                onValueChange = { username = it },
                label = "用户名",
                placeholder = "请输入用户名",
                required = true,
                maxLength = 20,
                validator = InputValidator { input ->
                    when {
                        input.isEmpty() -> ValidationResult(false, "用户名不能为空")
                        input.length < 3 -> ValidationResult(false, "用户名至少需要3个字符")
                        !input.matches(Regex("^[a-zA-Z0-9_]+$")) -> ValidationResult(false, "用户名只能包含字母、数字和下划线")
                        else -> ValidationResult(true)
                    }
                }
            )
            
            FormField(
                value = email,
                onValueChange = { email = it },
                label = "邮箱地址",
                placeholder = "请输入邮箱地址",
                required = true,
                type = TextFieldType.Email
            )
            
            FormField(
                value = phone,
                onValueChange = { phone = it },
                label = "手机号码",
                placeholder = "请输入手机号码",
                required = true,
                type = TextFieldType.Phone
            )
            
            PasswordField(
                value = password,
                onValueChange = { password = it },
                label = "密码",
                placeholder = "请输入密码",
                supportingText = "密码长度6-20位，包含字母和数字",
                validator = InputValidator { input ->
                    when {
                        input.isEmpty() -> ValidationResult(false, "密码不能为空")
                        input.length < 6 -> ValidationResult(false, "密码至少需要6个字符")
                        input.length > 20 -> ValidationResult(false, "密码最多20个字符")
                        !input.matches(Regex(".*[a-zA-Z].*")) -> ValidationResult(false, "密码必须包含字母")
                        !input.matches(Regex(".*\\d.*")) -> ValidationResult(false, "密码必须包含数字")
                        else -> ValidationResult(true)
                    }
                }
            )
            
            PasswordField(
                value = confirmPassword,
                onValueChange = { confirmPassword = it },
                label = "确认密码",
                placeholder = "请再次输入密码",
                validator = InputValidator { input ->
                    if (input != password) {
                        ValidationResult(false, "两次输入的密码不一致")
                    } else {
                        ValidationResult(true)
                    }
                }
            )
            
            Row(
                modifier = Modifier.fillMaxWidth(),
                verticalAlignment = Alignment.CenterVertically
            ) {
                Checkbox(
                    checked = agreeTerms,
                    onCheckedChange = { agreeTerms = it }
                )
                Text(
                    text = "我已阅读并同意《用户协议》和《隐私政策》",
                    style = MaterialTheme.typography.bodySmall,
                    modifier = Modifier.padding(start = 8.dp)
                )
            }
            
            Button(
                onClick = {
                    // 处理注册逻辑
                    println("注册: $username, $email, $phone")
                },
                modifier = Modifier.fillMaxWidth(),
                enabled = username.isNotBlank() && 
                         email.isNotBlank() && 
                         phone.isNotBlank() && 
                         password.isNotBlank() && 
                         confirmPassword == password && 
                         agreeTerms
            ) {
                Text("注册")
            }
        }
    }
}

@Preview(showBackground = true)
@Composable
fun TextFieldExamplesPreview() {
    MaterialTheme {
        TextFieldExamples()
    }
}

@Preview(showBackground = true)
@Composable
fun LoginFormExamplePreview() {
    MaterialTheme {
        LoginFormExample()
    }
}

@Preview(showBackground = true)
@Composable
fun RegisterFormExamplePreview() {
    MaterialTheme {
        RegisterFormExample()
    }
}